package net.mingsoft.expertmanage.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.mingsoft.expertmanage.dao.ProjectDao;
import net.mingsoft.expertmanage.entity.ProjectEntity;
import net.mingsoft.expertmanage.service.IProjectService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 项目管理服务实现类
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectDao, ProjectEntity> implements IProjectService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importExcel(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new Exception("请选择要导入的Excel文件");
        }
        
        String fileName = file.getOriginalFilename();
        if (fileName == null || !(fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))) {
            throw new Exception("文件格式不正确，请上传Excel文件");
        }
        
        InputStream inputStream = file.getInputStream();
        List<ProjectEntity> projectList = new ArrayList<>();
        
        // 使用EasyExcel读取数据
        EasyExcel.read(inputStream, ProjectEntity.class, new PageReadListener<ProjectEntity>(dataList -> {
            for (ProjectEntity project : dataList) {
                if (StringUtils.isNotBlank(project.getProjectCode())) {
                    projectList.add(project);
                }
            }
        })).sheet().doRead();
        
        if (projectList.isEmpty()) {
            return "Excel中没有有效数据";
        }
        
        // 批量保存数据
        this.saveBatch(projectList);
        
        return "成功导入" + projectList.size() + "条项目数据";
    }

    @Override
    public ProjectEntity getByProjectCode(String projectCode) {
        if (StringUtils.isEmpty(projectCode)) {
            return null;
        }
        
        QueryWrapper<ProjectEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_code", projectCode);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<ProjectEntity> getByExpertCode(String expertCode) {
        if (StringUtils.isEmpty(expertCode)) {
            return new ArrayList<>();
        }
        
        // 直接查询项目表中参与专家字段
        QueryWrapper<ProjectEntity> queryWrapper = new QueryWrapper<>();
        
        // MySQL中可以使用FIND_IN_SET函数查找逗号分隔的字段
        queryWrapper.apply("FIND_IN_SET({0}, participant_experts)", expertCode)
                  .or()
                  .eq("leader_code", expertCode); 
        
        return this.list(queryWrapper);
    }

    @Override
    public List<ProjectEntity> searchByKeyword(String keyword) {
        if (StringUtils.isEmpty(keyword)) {
            return new ArrayList<>();
        }
        
        QueryWrapper<ProjectEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("project_name", keyword).or()
                  .like("project_code", keyword).or()
                  .like("core_tech_keywords", keyword);
        
        return this.list(queryWrapper);
    }

    @Override
    public Integer getMaxSerialNo() {
        return baseMapper.getMaxSerialNo();
    }

    @Override
    public List<ProjectEntity> getByLeaderCode(String leaderCode) {
        if (StringUtils.isEmpty(leaderCode)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<ProjectEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectEntity::getLeaderCode, leaderCode);
        return this.list(queryWrapper);
    }
} 